<template>
	<view class="homePage">
		<!-- 工作台 -->
		<view class="homePage-title">
			<view class="name" @click="clickSelectProject">
				<view class="name-posi">
					<view class="box-height">
						<view class="title">{{ activeProject.name ? activeProject.name : "请选择业主" }}</view>
						<u-icon name="arrow-down" size="22px" color="#fff" class="icon-height"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view class="eventList" v-if="privileges.includes('app_menu_emergency_rescue')">
			<div class="content" :class="{scroll:eventList.length > 1}">
				<view class="event-title">
					<image class="image" src="/static/image/homePage/danger.png" alt=""></image>
					<view class="name">应急抢险</view>
					<view class="button" @click="getCreateEvent"
						v-if="buttonPrivileges.includes('app_menu_create_event')">创建</view>
				</view>
				<view class="center">
					<view class="event-con" v-for="item in eventList" :key="item.id">
						<view class="item">
							<view class="item-left">
								<view class="project">{{ item.bizProjectName || "" }}</view>
								<view class="siteName">{{ item.sectionName || "" }}/{{ item.siteName || "" }}</view>
							</view>
							<view class="item-right">
								<image class="image2" src="/static/image/homePage/arrow.png" mode=""
									@click="eventDetails(item)"></image>
							</view>
						</view>
						<view class="footer">
							<view class="orgName">{{ item.orgName || "" }}</view>
							<view class="time">{{item.startTime2 ||''}}</view>
						</view>
					</view>
				</view>
			</div>
		</view>
		<view
			:class="{'aa' : privileges.includes('app_menu_emergency_rescue'),'bb':!(privileges.includes('app_menu_emergency_rescue'))}">
			<view class="deviceBox" v-for="(item,index) in iconData"
				:class="{'active':index === 0 || eventList.length > 1 && index === 0,'active2':eventList.length === 0 && index === 0,'active3':eventList.length === 1 && index === 0}"
				:key="index">
				<view class="content">
					<view class="icon-title" v-show="privileges.includes(item.role)">{{item.title}}</view>
					<view class="icon-content">
						<view class="icon-item" v-for="value,index2) in item.children"
							v-show="buttonPrivileges.includes(value.role)" @click="toPage(value, item.title)"
							:key="index2">
							<view class="point">
								<image class="icon-img" :src="value.imgUrl" mode=""></image>
								<template v-if="value.title === '每日交底'">
									<text
										v-if="item.title === '工程维保' && dailyDisclosureCount.engineering">{{dailyDisclosureCount.engineering}}</text>
									<text
										v-else-if="item.title === '综合整治大修' && dailyDisclosureCount.overhaul">{{dailyDisclosureCount.overhaul}}</text>
								</template>
								<template v-if="value.title === '条件验收'">
									<text
										v-if="item.title === '工程维保' && conditionCount.engineering">{{ conditionCount.engineering }}</text>
									<text
										v-else-if="item.title === '综合整治大修' && conditionCount.overhaul">{{ conditionCount.overhaul }}</text>
								</template>
								<template v-if="value.title === '病害維修' && hongKong.repair">
									<text>{{hongKong.repair }}</text>
								</template>
								<template v-if="value.title === '維修記錄' && hongKong.record">
									<text>{{hongKong.record }}</text>
								</template>
							</view>
							<view class="name">{{ value.title }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-picker :show="show" :columns="columns" keyName="name" @cancel="show=false" :immediateChange="true"
			@confirm="projectSelected"></u-picker>
	</view>
</template>

<script>
	import iconData from './itemConfig.js'
	import {
		singleProjectList
	} from '@/api/project/project'
	import {
		getListByNameByLike
	} from "@/api/emergency/emergencyDispatch.js"
	import {
		mapGetters
	} from "vuex"
	import getData from '@/utils/getData.js'
	import {
		doCache
	} from '@/utils/offline/index.js'
	import {
		initCache,
		cacheStatus,
		cacheLevels,
		RepairMeasure,
		cacheOrderList,
		detailList,
		dictionaryCache,
		cache_imgs
	} from "@/utils/offline/cache.js"
	import {
		getFillRecordNotUploadCount
	} from "@/api/engineeringMaintenance/engineeringMaintenance.js";
	import {
		getConstructionPlanList
	} from "@/api/conditionalAcceptance/constructionPlan.js"
	import {
		hkRepairPlan_list,
		hkRepairTask_getRepairRecord
	} from "@/api/HongKong/hkAttendanceSheet.js";
	// #ifdef APP-PLUS
	import {
		before
	} from "./cacheGradeAndContent.js"
	// #endif
	export default {
		computed: {
			...mapGetters(['buttonPrivileges']),
			...mapGetters(['privileges'])
		},
		data() {
			return {
				iconData,
				show: false,
				columns: [],
				activeProject: {},
				activeEvent: {},
				eventList: [], // 事件列表
				// 每日交底数量
				dailyDisclosureCount: {
					engineering: 0,
					overhaul: 0,
				},
				conditionCount: {
					engineering: 0,
					overhaul: 0
				},
				hongKong: {
					repair: 0,
					record: 0
				}
			}
		},
		watch: {
			activeProject: {
				handler(newVal) {
					if (newVal && newVal.id) {
						// 获取条件验收统计数量
						this.getConstructionPlanList('gcwb', newVal.id)
						this.getConstructionPlanList('zhdx', newVal.id)
					}
				},
				immediate: true
			}
		},
		async onShow() {
			this.getProjectList()
			uni.setStorageSync("isShowPopup", "1")
			// 获取每日交底统计的数量...
			this.dailyDisclosureCount.engineering = await this.handleGetFillRecordNotUploadCount("gcwb");
			this.dailyDisclosureCount.overhaul = await this.handleGetFillRecordNotUploadCount("zhdx");
			this.hongKong.repair = await this.getBadgeNumber()
			this.hongKong.record = await this.getRecordNum()
		},
		methods: {
			/** 统计未完成条件验收的数量 */
			getConstructionPlanList(code, id) {
				getConstructionPlanList({
					currPage: 1,
					pageSize: 1,
					params: {
						orderStatusList: ['acceptance_status_not_started', 'acceptance_status_in_progress',
							'acceptance_status_audit', 'acceptance_status_agree', 'acceptance_status_disagree'
						],
						code,
						projectId: id,
						state: 1
					}
				}).then(res => {
					if (code === 'gcwb') {
						this.conditionCount.engineering = res.result.total
					} else if (code === 'zhdx') {
						this.conditionCount.overhaul = res.result.total
					}
				})
			},

			/** 获取统计未上传的需填报记录数量 */
			handleGetFillRecordNotUploadCount(type) {
				return new Promise(resolve => {
					if (uni.getStorageSync("isOwner")) {
						getFillRecordNotUploadCount({
							objType: type,
							projectId: uni.getStorageSync("isOwner")
						}).then(res => {
							resolve(res.result);
						});
					} else {
						resolve(0);
					}
				});
			},
			getBadgeNumber() {
				return new Promise(resolve => {
					if (uni.getStorageSync("isOwner")) {
						hkRepairPlan_list({
							currPage: 1,
							pageSize: 99999,
							params: {
								isFinish: false,
								repairDate: undefined,
								projectId: uni.getStorageSync("isOwner"),
								isDefaultQuery: true
							},
						}).then(res => {
							console.log(res);
							resolve(res.result.list.length || 0);
						});
					} else {
						resolve(0);
					}
				});
			},
			getRecordNum() {
				return new Promise(resolve => {
					if (uni.getStorageSync("isOwner")) {
						hkRepairTask_getRepairRecord({
							currPage: 1,
							pageSize: 1,
							params: {
								taskStates: ['task_state_xfg'],
								projectId: uni.getStorageSync('isOwner')
							}
						}).then(res => {
							resolve(res.result.total);
						});
					} else {
						resolve(0);
					}
				});
			},
			// 创建应急抢险事件
			getCreateEvent() {
				// user_groupId   === 1 时, 应急抢险 设备材料管理 都不加  projectId
				// user_groupId  不等于1时, 应急抢险 加上 projectId,  设备材料管理 不加projectId
				// 判断 user_groupId 是否等于  1
				if (!this.activeProject.id) {
					this.$message("请选择业主")
					return
				}
				let groupId = Number(uni.getStorageSync("user_groupId") || 0)
				if (groupId === 1) {
					uni.removeStorageSync("isOwner")
				} else {
					uni.setStorageSync("isOwner", this.activeProject.id)
					uni.setStorageSync("ownerCode", this.activeProject.code)
					uni.setStorageSync("isShowPopup", this.activeProject.id)
				}
				uni.navigateTo({
					url: "/subpackage-emergency/pages/createEmergency"
				})
			},

			// 点击跳转 到事件操作详情
			eventDetails(item) {
				if (!this.activeProject.id) {
					this.$message("请选择业主")
					return
				}
				uni.setStorageSync('isYanLian', item.isRehearsal)
				uni.navigateTo({
					url: `/subpackage-emergency/pages/eventDetails?eventId=${item.id}&&isRehearsal=${item.isRehearsal}`,
					success: (res) => {
						res.eventChannel.emit('setData', {
							data: item
						})
					}
				})
			},

			//点击选择业主按钮
			clickSelectProject() {
				if (this.columns[0]) {
					this.show = true
				}

			},
			//业主选择器返回值
			async projectSelected(array) {
				this.activeProject = array.value[0]
				// 切换业主,  存储业主id,  刷新事件列表
				uni.setStorageSync("isOwner", this.activeProject.id)
				uni.setStorageSync("ownerCode", this.activeProject.code)
				uni.setStorageSync("isShowPopup", this.activeProject.id)
				this.getEventList(this.activeProject.id || null)
				this.show = false
				// #ifdef APP-PLUS
				if (this.activeProject.id) {
					await before({
						projectId: this.activeProject.id
					})
				} else {
					uni.showToast({
						title: "暂未获取到业主信息",
						icon: 'none',
						mask: true
					})
				}
				// #endif
				this.dailyDisclosureCount.engineering = await this.handleGetFillRecordNotUploadCount("gcwb");
				this.dailyDisclosureCount.overhaul = await this.handleGetFillRecordNotUploadCount("zhdx");
				this.hongKong.repair = await this.getBadgeNumber()
				this.hongKong.record = await this.getRecordNum()
			},

			// 获取 当前用户下 业主列表
			getProjectList() {
				singleProjectList({}).then(async data => {
					if (data.success && data.result && data.result.length > 0) {
						this.columns = [data.result]
						let isOwner = uni.getStorageSync("isOwner")
						if (isOwner) {
							this.activeProject = data.result.find(item => item.id == isOwner)
						} else {
							this.activeProject = data.result[0]
							if (data.result.length > 1) {
								this.show = true
							}
						}

						uni.setStorageSync("isShowPopup", this.activeProject.id)
						uni.setStorageSync("isOwner", this.activeProject.id)
						uni.setStorageSync("ownerCode", this.activeProject.code)
						this.getEventList(this.activeProject.id || null)
						// #ifdef APP-PLUS
						if (this.activeProject.id) {
							await before({
								projectId: this.activeProject.id
							})
						} else {
							uni.showToast({
								title: "暂未获取到业主信息",
								icon: 'none',
								mask: true
							})
						}
						// #endif
					}
				})
			},

			// 通过业主id 获取事件列表
			async getEventList(projectId) {
				let _query = {
					currPage: 1,
					pageSize: 10000,
					params: {
						orgId: "", // 组织id
						state: 0,
						projectId: projectId
					}
				}
				const res = await getListByNameByLike(_query)
				if (res.result) {
					res.result.list.forEach(item => {
						item.startTime2 = this.getDate(item.startTime)
						switch (item.state) {
							case 0:
								item.stateText = '处置中'
								break
							case 1:
								item.stateText = '归档'
								break
						}
					})
					this.eventList = res.result.list
				}
				// console.log(this.eventList, '历史事件列表');
			},

			async toPage(obj, title) {
				console.log(obj, "obj");
				if (obj.isRequireOwner && !this.activeProject.id) {
					return uni.showToast({
						title: "请选择业主！",
						icon: 'none',
						mask: true
					})
				}
				let page = obj.page
				uni.setStorageSync("isShowPopup", this.activeProject.id)
				if (title !== "应急抢险") {
					uni.removeStorageSync("isShowPopup")
					uni.navigateTo({
						url: page
					})
				} else {
					uni.navigateTo({
						url: page + "?eventId=" + this.activeEvent.id,
						success: (res) => {
							res.eventChannel.emit('setData', {
								data: this.activeEvent
							})
						}
					})
				}
			},

			// 转换日期 获得年月日
			getDate(date) {
				if (!date) return ''
				var d = new Date(date)
				const y = d.getFullYear()
				let m = d.getMonth() + 1
				let did = d.getDate()
				let h = d.getHours()
				if (m < 10) {
					m = '0' + m
				}
				if (did < 10) {
					did = '0' + did
				}
				if (h < 10) {
					h = '0' + h
				}
				let minute = d.getMinutes()
				if (minute < 10) {
					minute = '0' + minute
				}
				let second = d.getSeconds()
				if (second < 10) {
					second = '0' + second
				}
				return y + '-' + m + '-' + did + ' ' + h + ':' + minute + ':' + second
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
		width: 100%;
	}

	body {
		width: 100%;
		height: 100%;
	}

	.homePage {
		position: relative;
		background-color: #F5F7FA;
		width: 100%;
		padding-bottom: 140rpx;
		/* #ifdef MP-WEIXIN */
		padding-bottom: 60rpx;
		/* #endif */
		// height: 100%;

		.point {
			position: relative;

			>text {
				width: 36upx;
				height: 36upx;
				background: #ff6a6a;
				border-radius: 50%;
				color: #fff;
				position: absolute;
				font-weight: 500;
				font-size: 24upx;
				text-align: center;
				line-height: 36upx;
				transform: translate(-50%, -30%);
				top: 0;
				right: 0;
			}
		}
	}

	.homePage-title {
		display: flex;
		height: 360rpx;
		background-color: #2F80ED;
		padding: 0rpx 32rpx;

		.name {
			margin-top: 60rpx;
			height: 120rpx;
			line-height: 120rpx;
			display: flex;
			font-size: 36rpx;
			align-items: center;
			margin-left: 14rpx;
			color: #fff;
			cursor: pointer;

			.name-posi {
				.box-height {
					width: 100vw;
					display: flex;
					padding-left: 30px;
					align-items: center;
					height: 200rpx;
					background-color: rgb(47, 128, 237);
					position: fixed;
					z-index: 999;
					top: 0;
					left: 0;
					/* #ifdef MP-WEIXIN */
					padding-top: 20rpx;
					/* #endif */
				}

				.title {
					margin-right: 10rpx;
				}
			}

			.icon-height {
				/* #ifdef MP-WEIXIN */
				height: 80rpx;
				line-height: 80rpx;
				/* #endif */
			}

		}

		.none {
			flex: 1;
		}
	}

	.eventList {
		position: absolute;
		top: 200rpx;
		left: 30rpx;
		width: calc(100% - 60rpx);
		height: 700rpx;

		.content {
			background-color: #fff;
			box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(47, 128, 237, 0.2500);
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			width: 100%;
			// height: 700rpx;
			overflow-y: auto;

			.event-title {
				position: absolute;
				/* #ifdef MP-WEIXIN */
				top: 32rpx;
				/* #endif */
				left: 0rpx;
				width: 100%;
				z-index: 1;
				display: flex;
				align-items: center;
				padding: 30rpx 0rpx;
				border-bottom: 2rpx solid #E2E5ED;
				background-color: #fff;

				.image {
					width: 70rpx;
					height: 70rpx;
					margin-left: 45rpx;
					margin-right: 32rpx;
				}

				.name {
					font-size: 36rpx;
					font-weight: bold;
					color: #223247;
					flex: 1;
				}

				.button {
					width: 128rpx;
					height: 60rpx;
					background-color: #63D48C;
					border-radius: 4rpx 4rpx 4rpx 4rpx;
					color: #fff;
					line-height: 60rpx;
					text-align: center;
					margin-right: 30rpx;
					cursor: pointer;
				}
			}

			.center {
				margin-top: 132rpx;
			}

			.event-con {
				padding: 45rpx 32rpx;
				border-bottom: 2rpx solid #E2E5ED;

				.item {
					display: flex;
					align-items: center;

					.item-left {
						padding-left: 15rpx;
						width: 400rpx;
						font-size: 32rpx;
						font-weight: normal;
						color: #22204E;

						.project {
							width: 400rpx;
							overflow: hidden; //超出的文本隐藏
							text-overflow: ellipsis; //溢出用省略号显示
							white-space: nowrap; //溢出则不换行
						}

						.siteName {
							width: 400rpx;
							color: #445469;
							margin-top: 14rpx;
							overflow: hidden; //超出的文本隐藏
							text-overflow: ellipsis; //溢出用省略号显示
							white-space: nowrap; //溢出则不换行
						}
					}

					.item-right {
						flex: 1;
						text-align: right;

						.image2 {
							width: 80rpx;
							height: 80rpx;
							margin-right: 15rpx;
						}
					}
				}

				.footer {
					display: flex;
					align-items: center;
					font-size: 28rpx;
					font-weight: normal;
					color: #6A819E;
					margin-top: 45rpx;

					.orgName {
						width: 300rpx;
						overflow: hidden; //超出的文本隐藏
						text-overflow: ellipsis; //溢出用省略号显示
						white-space: nowrap; //溢出则不换行
						padding-left: 15rpx;
						margin-right: 25rpx;
					}

					.time {
						width: 280rpx;
						text-align: center;
					}
				}
			}
		}

		.content.scroll {
			height: 700rpx;
		}
	}

	.active {
		margin-top: 590rpx !important;
	}

	.active2 {
		margin-top: 30rpx !important;
	}

	.active3 {
		margin-top: 280rpx !important;
	}

	.deviceBox {
		padding: 0rpx 32rpx;
		margin-top: 30rpx;

		.content {
			background-color: #fff;
			box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(47, 128, 237, 0.2500);
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			width: 100%;
		}

		.icon-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #223247;
			margin-left: 32rpx;
			padding: 28rpx 0rpx;
		}

		.icon-content {
			margin-top: 15rpx;
			display: flex;
			flex-wrap: wrap;

			.icon-item {
				text-align: center;
				width: 25%;

				.icon-img {
					width: 100rpx;
					height: 88rpx;
				}

				.name {
					font-size: 28rpx;
					font-weight: bold;
					color: #445469;
					margin-top: 10rpx;
					margin-bottom: 30rpx;
				}
			}
		}
	}

	.bb {
		margin-top: -300rpx;

		.active {
			margin-top: 0 !important;
		}
	}
</style>